var express = require('express');
var router = express.Router();
var models = require('../models')
var Op = models.Sequelize.Op

/* GET departments listing. */
router.get('/', async function (req, res, next) {
    try {
        var departments = await models.Department.findAll()
        res.json({ departments })
    } catch (e) {
        console.log(e);
    }
});

// 获取用户提交的信息并插入数据库
router.post('/', async function (req, res, next) {
    const { departmentName } = JSON.parse(req.query.data)
    try {
        var department = await models.Department.create({
            departmentName
        })
        res.json({ department })
    } catch (e) {
        console.log(e)
    }
})

// 修改部门信息
router.put('/:id', async function (req, res, next) {
    const id = req.params.id
    const { departmentName } = JSON.parse(req.query.data)
    try {
        var department = await models.Department.update({
            departmentName
        }, { where: { id } })

        res.json({ department })
    } catch (e) {
        console.log(e)
    }
})

// 删除部门信息
router.delete('/:id', async function (req, res, next) {
    const id = req.params.id
    var department = await models.Department.findByPk(id)
    if (department) {
        department.destroy()
        res.json({ msg: '删除成功' })
    } else {
        res.json({ msg: '不存在该数据' })
    }
})

module.exports = router;
